package com.baizhi.config;

import com.baizhi.realmDemo.RealmDemo;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

//创建一个shiro的配置类
@Configuration
public class ShiroConfig {

    //创建一个过滤器
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager def) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //设置过滤器链 在shiro实际上就是 设置过滤规则

        // 过滤链 书写过滤规则 哪些要拦截 哪些不拦截
        Map map = new HashMap();
        //// 设置过滤规则 需要自己改
        // anon 匿名可访问 不用登录就可以访问
        // authc 认证后可访问 登录后可以访问
        map.put("/login.jsp", "anon");
        map.put("/zc.jsp", "anon");
        map.put("/login", "anon");
        map.put("/zc", "anon");
        // 代表所有的都需要认证
        map.put("/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        //设置SecurityManager
        shiroFilterFactoryBean.setSecurityManager(def);
        return shiroFilterFactoryBean;
    }

    /**
     * 创建SecurityManager
     */
    @Bean
    public DefaultWebSecurityManager getSecurityManager(RealmDemo re) {

        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //设置之定义的realm
        defaultWebSecurityManager.setRealm(re);
        return defaultWebSecurityManager;
    }

    /**
     * 创建自定义的realm
     */

    @Bean
    public RealmDemo getReal(CredentialsMatcher cre) {
        RealmDemo realmDemo = new RealmDemo();
        //加密处理设置密码凭证器
        realmDemo.setCredentialsMatcher(cre);

        return realmDemo;
    }

    /**
     * 设置密码凭证器
     * @return
     */
    @Bean
    public CredentialsMatcher getCredentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5");
        credentialsMatcher.setHashIterations(1024);
        return credentialsMatcher;
    }

}
